﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Client.Services;

namespace XRM.Framework.Test.Integration
{
    public abstract class XrmIntegrationTest
    {
        #region Instance Variables

        private IOrganizationService _service;
        private CrmConnection _connection;

        #endregion

        #region Constructors

        public XrmIntegrationTest()
        {
        }

        public XrmIntegrationTest(IOrganizationService service)
        {
            _service = service;
        }

        #endregion

        #region Properties

        protected IOrganizationService OrganizationService
        {
            get
            {
                if (_service == null)
                {
                    _service = new OrganizationService(Connection);
                }
                return _service;
            }
        }

        protected CrmConnection Connection
        {
            get
            {
                if (_connection == null)
                {
                    _connection = new CrmConnection("Xrm");
                }
                return _connection;
            }
        }

        protected OrganizationRequest TriggerRequest
        {
            get;
            private set;
        }

        protected OrganizationResponse TriggerResponse
        {
            get;
            private set;
        }

        #endregion

        #region Methods

        protected virtual void Test()
        {
            Setup();
            Do();
            Verify();
        }
        
        protected virtual void Setup()
        {
        }

        protected virtual void Do()
        {
            TriggerRequest = SetupTriggerRequest();

            if (!TriggerRequest.RequestId.HasValue)
            {
                TriggerRequest.RequestId = Guid.NewGuid();
            }

            TriggerResponse = OrganizationService.Execute(TriggerRequest);
        }

        #endregion

        #region Abstract Methods

        protected abstract void Verify();
        protected abstract OrganizationRequest SetupTriggerRequest();

        #endregion
    }
}
